import * as React from 'react';

export interface IProps {
  name?: string;
  age?: number;
  inputRef?: any;
}
class User extends React.Component<IProps> {
  private inputElement: any;

  static sayHello() {
    console.error('hello world'); // tslint:disable-line
  }

  constructor(props: IProps) {
    super(props);
    this.focus = this.focus.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  state = {
    name: '',
    age: 0,
  };

  componentDidMount() {
    this.setState({
      name: this.props.name,
      // https://stackoverflow.com/questions/67430850/warning-a-component-is-changing-a-controlled-input-to-be-uncontrolled-in-react?rq=1
      age: this.props.age || 0,
    });
  }

  onChange = (e: any) => {
    this.setState({
      age: e.target.value,
    });
  };

  focus() {
    this.inputElement.focus();
  }

  render() {
    return (
      <div>
        <div>姓名：{this.state.name}</div>
        <div>
          年龄:
          <input
            value={this.state.age}
            onChange={this.onChange}
            type="number"
            ref={(input) => {
              if (this.props.inputRef) {
                this.props.inputRef(input); // 调用父组件传入的ref回调函数
              }
              this.inputElement = input;
            }}
          />
        </div>
        <div>
          <button onClick={this.focus}>获取输入框焦点</button>
        </div>
      </div>
    );
  }
}

export default User;
